import Vue from 'vue'
import router,{ staticRoutes,dynamicRoutes,filterRoute } from '@/router'

const state = {
  token: sessionStorage.getItem('token') || '',
  userInfo: JSON.parse(sessionStorage.getItem('userInfo')) || {},
  // 菜单列表
  menuList: JSON.parse(sessionStorage.getItem('menu')) || []
}

const mutations = {
  // 存储token
  SET_TOKEN: (state, token) => {
    state.token = token
    sessionStorage.setItem('token',token)
  },
  // 存储用户信息
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    sessionStorage.setItem('userInfo',JSON.stringify(userInfo))
  },
  // 设置菜单列表
  SET_SIDEBAR_LIST: (state,list) => {
    state.menuList = list
  }
}

const actions = {
  // 登录
  login({ commit,dispatch },userInfo){
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      Vue.axios.post('LOGIN',{ username: username.trim(), password: password },false).then(result => {
        commit('SET_TOKEN',result.data.token)
        commit('SET_USER_INFO',{
          avatar: result.data.avatar,
          name: result.data.name
        })
        resolve()
        // 根据用户权限设置路由和菜单列表
        dispatch('setSidebarList',result.data.menu)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 根据用户权限设置路由和菜单列表
  setSidebarList({ commit },menu){
    let route = filterRoute(dynamicRoutes,menu)
    commit('SET_SIDEBAR_LIST',staticRoutes.concat(route))
    //动态添加路由
    router.addRoutes(route)
    // 缓存菜单到本地
    sessionStorage.setItem('menu',JSON.stringify(staticRoutes.concat(route)))
  },
  // 退出登录
  logout({commit,dispatch}){
    commit('SET_TOKEN','')
    commit('SET_USER_INFO',{})
    commit('SET_SIDEBAR_LIST',[])
    dispatch('tagsView/clearAll',{},{ root: true })
    sessionStorage.clear()
    router.push({ path: '/login' })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}